<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频播放结束诊断工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .video-container {
            width: 100%;
            max-width: 800px;
            margin: 20px 0;
        }
        video {
            width: 100%;
            height: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .log {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 15px;
            font-family: monospace;
            font-size: 12px;
            max-height: 400px;
            overflow-y: auto;
            white-space: pre-wrap;
        }
        .error { color: #dc3545; font-weight: bold; }
        .success { color: #28a745; font-weight: bold; }
        .warning { color: #ffc107; font-weight: bold; }
        .info { color: #17a2b8; }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover { background: #0056b3; }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .api-test {
            margin: 10px 0;
            padding: 10px;
            border: 1px solid #eee;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <h1>🎬 视频播放结束诊断工具</h1>
    
    <div class="container">
        <h2>问题分析</h2>
        <div class="test-section">
            <h3>🔍 问题根源分析：</h3>
            <p><strong>视频播放完成后出现解码错误</strong>，这通常是由以下原因造成的：</p>
            <ol>
                <li><strong>API调用失败</strong>：视频播放结束后调用 <code>/api/video-view/record</code> 和 <code>/api/learning/complete</code> 失败</li>
                <li><strong>数据库表不存在</strong>：<code>video_view_record</code> 或 <code>learning_record</code> 表可能不存在</li>
                <li><strong>权限问题</strong>：用户会话可能已过期</li>
                <li><strong>数据格式错误</strong>：传递给API的数据格式不正确</li>
                <li><strong>网络请求异常</strong>：API请求过程中发生网络错误</li>
            </ol>
        </div>
    </div>

    <div class="container">
        <h2>视频播放测试</h2>
        <div class="video-container">
            <video id="testVideo" controls preload="metadata">
                <source src="/api/video/stream/d895a1d5-aded-4ffe-8087-6da01af4ddbc.mp4" type="video/mp4">
                您的浏览器不支持视频播放。
            </video>
        </div>
        <button onclick="startDiagnostic()">开始诊断</button>
        <button onclick="testAPIs()">测试API</button>
        <button onclick="simulateVideoEnd()">模拟播放结束</button>
        <button onclick="clearLog()">清空日志</button>
    </div>

    <div class="container">
        <h2>API测试</h2>
        <div class="api-test">
            <h4>测试观看记录API</h4>
            <button onclick="testVideoViewAPI()">测试 /api/video-view/record</button>
            <div id="videoViewResult"></div>
        </div>
        <div class="api-test">
            <h4>测试学习完成API</h4>
            <button onclick="testLearningCompleteAPI()">测试 /api/learning/complete</button>
            <div id="learningCompleteResult"></div>
        </div>
    </div>

    <div class="container">
        <h2>诊断日志</h2>
        <div id="log" class="log"></div>
    </div>

    <script>
        const video = document.getElementById('testVideo');
        const log = document.getElementById('log');
        let watchStartTime = null;
        let totalWatchDuration = 0;
        
        function addLog(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const className = type === 'error' ? 'error' : 
                            type === 'success' ? 'success' : 
                            type === 'warning' ? 'warning' : 'info';
            log.innerHTML += `<span class="${className}">[${timestamp}] ${message}</span>\n`;
            log.scrollTop = log.scrollHeight;
        }
        
        function clearLog() {
            log.innerHTML = '';
        }
        
        // 视频事件监听
        video.addEventListener('loadstart', () => {
            addLog('🔄 开始加载视频', 'info');
        });
        
        video.addEventListener('loadedmetadata', () => {
            addLog(`✅ 视频元数据加载成功 - 时长: ${video.duration}秒`, 'success');
        });
        
        video.addEventListener('play', () => {
            addLog('▶️ 视频开始播放', 'success');
            watchStartTime = Date.now();
        });
        
        video.addEventListener('pause', () => {
            addLog('⏸️ 视频暂停', 'info');
            recordWatchDuration();
        });
        
        video.addEventListener('ended', () => {
            addLog('🏁 视频播放结束', 'success');
            recordWatchDuration();
            completeLearning();
        });
        
        video.addEventListener('error', (e) => {
            const error = video.error;
            let errorMsg = '❌ 视频播放错误: ';
            
            if (error) {
                switch (error.code) {
                    case 1:
                        errorMsg += 'MEDIA_ERR_ABORTED - 视频加载被中止';
                        break;
                    case 2:
                        errorMsg += 'MEDIA_ERR_NETWORK - 网络错误';
                        break;
                    case 3:
                        errorMsg += 'MEDIA_ERR_DECODE - 视频解码错误';
                        break;
                    case 4:
                        errorMsg += 'MEDIA_ERR_SRC_NOT_SUPPORTED - 视频格式不支持';
                        break;
                    default:
                        errorMsg += `未知错误 (代码: ${error.code})`;
                }
            }
            
            addLog(errorMsg, 'error');
            addLog(`网络状态: ${video.networkState}, 就绪状态: ${video.readyState}`, 'error');
        });
        
        // 记录观看时长
        async function recordWatchDuration() {
            if (!watchStartTime) return;
            
            const duration = Math.floor((Date.now() - watchStartTime) / 1000);
            totalWatchDuration += duration;
            watchStartTime = null;
            
            addLog(`📊 记录观看时长: ${duration}秒`, 'info');
            
            try {
                const response = await fetch('/api/video-view/record', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        videoId: 1, // 假设视频ID为1
                        watchDuration: duration
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    addLog(`✅ 观看记录保存成功: ${result.message}`, 'success');
                } else {
                    addLog(`❌ 观看记录保存失败: ${result.message}`, 'error');
                }
            } catch (error) {
                addLog(`❌ 观看记录API调用失败: ${error.message}`, 'error');
            }
        }
        
        // 完成学习
        async function completeLearning() {
            addLog('🎓 开始完成学习记录', 'info');
            
            try {
                const response = await fetch('/api/learning/complete', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        videoId: 1 // 假设视频ID为1
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    addLog(`✅ 学习完成记录保存成功: ${result.message}`, 'success');
                } else {
                    addLog(`❌ 学习完成记录保存失败: ${result.message}`, 'error');
                }
            } catch (error) {
                addLog(`❌ 学习完成API调用失败: ${error.message}`, 'error');
            }
        }
        
        // 测试函数
        function startDiagnostic() {
            addLog('=== 🚀 开始视频播放结束诊断 ===', 'info');
            addLog('请播放视频并等待播放结束，观察API调用情况', 'info');
        }
        
        async function testAPIs() {
            addLog('=== 🔍 测试API端点 ===', 'info');
            await testVideoViewAPI();
            await testLearningCompleteAPI();
        }
        
        async function testVideoViewAPI() {
            addLog('🔍 测试观看记录API...', 'info');
            try {
                const response = await fetch('/api/video-view/record', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        videoId: 1,
                        watchDuration: 10
                    })
                });
                
                const result = await response.json();
                document.getElementById('videoViewResult').innerHTML = 
                    `<div class="${result.success ? 'success' : 'error'}">${result.success ? '✅' : '❌'} ${result.message}</div>`;
                
                addLog(`📊 观看记录API响应: ${JSON.stringify(result)}`, result.success ? 'success' : 'error');
            } catch (error) {
                document.getElementById('videoViewResult').innerHTML = 
                    `<div class="error">❌ API调用失败: ${error.message}</div>`;
                addLog(`❌ 观看记录API调用异常: ${error.message}`, 'error');
            }
        }
        
        async function testLearningCompleteAPI() {
            addLog('🔍 测试学习完成API...', 'info');
            try {
                const response = await fetch('/api/learning/complete', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        videoId: 1
                    })
                });
                
                const result = await response.json();
                document.getElementById('learningCompleteResult').innerHTML = 
                    `<div class="${result.success ? 'success' : 'error'}">${result.success ? '✅' : '❌'} ${result.message}</div>`;
                
                addLog(`📊 学习完成API响应: ${JSON.stringify(result)}`, result.success ? 'success' : 'error');
            } catch (error) {
                document.getElementById('learningCompleteResult').innerHTML = 
                    `<div class="error">❌ API调用失败: ${error.message}</div>`;
                addLog(`❌ 学习完成API调用异常: ${error.message}`, 'error');
            }
        }
        
        function simulateVideoEnd() {
            addLog('🎭 模拟视频播放结束事件', 'info');
            recordWatchDuration();
            completeLearning();
        }
        
        // 页面加载时自动开始
        window.addEventListener('load', () => {
            addLog('=== 🎬 视频播放结束诊断工具启动 ===', 'info');
            addLog('📋 请按照以下步骤进行诊断：', 'info');
            addLog('1. 点击"测试API"按钮检查API端点是否正常', 'info');
            addLog('2. 点击"开始诊断"按钮', 'info');
            addLog('3. 播放视频并等待播放结束', 'info');
            addLog('4. 观察日志中的API调用结果', 'info');
        });
    </script>
</body>
</html>
